<template>
  <div class="permission-management">
    <!-- 页面标题和操作按钮 -->
    <div class="page-header">
      <h2>权限管理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增权限
        </el-button>
        <el-button @click="handleBatchDelete" :disabled="!selectedPermissions.length">
          <el-icon><Delete /></el-icon>
          批量删除
        </el-button>
        <el-button @click="handleExpandAll">
          <el-icon><ArrowDown /></el-icon>
          展开全部
        </el-button>
        <el-button @click="handleCollapseAll">
          <el-icon><ArrowUp /></el-icon>
          收起全部
        </el-button>
        <el-button @click="handleExport">
          <el-icon><Download /></el-icon>
          导出
        </el-button>
      </div>
    </div>

    <!-- 搜索筛选区域 -->
    <div class="search-section">
      <el-form :model="searchForm" inline>
        <el-form-item label="权限名称">
          <el-input v-model="searchForm.name" placeholder="请输入权限名称" clearable />
        </el-form-item>
        <el-form-item label="权限编码">
          <el-input v-model="searchForm.code" placeholder="请输入权限编码" clearable />
        </el-form-item>
        <el-form-item label="权限类型">
          <el-select v-model="searchForm.type" placeholder="请选择权限类型" clearable>
            <el-option label="菜单" value="menu" />
            <el-option label="按钮" value="button" />
            <el-option label="接口" value="api" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="启用" value="1" />
            <el-option label="禁用" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 权限树表格 -->
    <div class="table-section">
      <el-table
        :data="tableData"
        v-loading="loading"
        @selection-change="handleSelectionChange"
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        :expand-row-keys="expandedKeys"
        stripe
        border
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="权限名称" min-width="200">
          <template #default="{ row }">
            <div class="permission-name">
              <el-icon v-if="row.type === 'menu'" class="permission-icon">
                <Menu />
              </el-icon>
              <el-icon v-else-if="row.type === 'button'" class="permission-icon">
                <Operation />
              </el-icon>
              <el-icon v-else-if="row.type === 'api'" class="permission-icon">
                <Link />
              </el-icon>
              <span>{{ row.name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="code" label="权限编码" width="180" />
        <el-table-column prop="type" label="权限类型" width="100">
          <template #default="{ row }">
            <el-tag
              :type="row.type === 'menu' ? 'primary' : row.type === 'button' ? 'success' : 'warning'"
              size="small"
            >
              {{ getTypeLabel(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="path" label="路径/接口" min-width="150" />
        <el-table-column prop="method" label="请求方式" width="100">
          <template #default="{ row }">
            <el-tag v-if="row.method" :type="getMethodType(row.method)" size="small">
              {{ row.method }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="sort" label="排序" width="80" />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'" size="small">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button
              v-if="row.type === 'menu'"
              type="success"
              size="small"
              @click="handleAddChild(row)"
            >
              添加子权限
            </el-button>
            <el-button
              :type="row.status === 1 ? 'danger' : 'success'"
              size="small"
              @click="handleToggleStatus(row)"
            >
              {{ row.status === 1 ? '禁用' : '启用' }}
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 新增/编辑权限对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="700px"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="权限名称" prop="name">
              <el-input v-model="formData.name" placeholder="请输入权限名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="权限编码" prop="code">
              <el-input v-model="formData.code" placeholder="请输入权限编码" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="权限类型" prop="type">
              <el-select v-model="formData.type" placeholder="请选择权限类型" @change="handleTypeChange">
                <el-option label="菜单" value="menu" />
                <el-option label="按钮" value="button" />
                <el-option label="接口" value="api" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上级权限" prop="parentId">
              <el-tree-select
                v-model="formData.parentId"
                :data="parentOptions"
                :props="treeSelectProps"
                placeholder="请选择上级权限"
                clearable
                check-strictly
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="路径/接口" prop="path">
              <el-input v-model="formData.path" :placeholder="getPathPlaceholder()" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="formData.type === 'api'">
            <el-form-item label="请求方式" prop="method">
              <el-select v-model="formData.method" placeholder="请选择请求方式">
                <el-option label="GET" value="GET" />
                <el-option label="POST" value="POST" />
                <el-option label="PUT" value="PUT" />
                <el-option label="DELETE" value="DELETE" />
                <el-option label="PATCH" value="PATCH" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-else>
            <el-form-item label="图标" prop="icon">
              <el-input v-model="formData.icon" placeholder="请输入图标名称" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="排序" prop="sort">
              <el-input-number v-model="formData.sort" :min="0" :max="999" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="formData.status">
                <el-radio :label="1">启用</el-radio>
                <el-radio :label="0">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="formData.type === 'menu'">
            <el-form-item label="是否隐藏">
              <el-switch v-model="formData.hidden" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="权限描述">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="3"
            placeholder="请输入权限描述"
          />
        </el-form-item>

        <el-form-item label="备注">
          <el-input
            v-model="formData.remark"
            type="textarea"
            :rows="2"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Delete,
  Download,
  Search,
  Refresh,
  Menu,
  Operation,
  Link,
  ArrowDown,
  ArrowUp
} from '@element-plus/icons-vue'

// 响应式数据
const loading = ref(false)
const submitLoading = ref(false)
const dialogVisible = ref(false)
const selectedPermissions = ref([])
const formRef = ref()
const expandedKeys = ref([])
const parentOptions = ref([])

// 搜索表单
const searchForm = reactive({
  name: '',
  code: '',
  type: '',
  status: ''
})

// 表单数据
const formData = reactive({
  id: null,
  name: '',
  code: '',
  type: 'menu',
  parentId: null,
  path: '',
  method: '',
  icon: '',
  sort: 0,
  status: 1,
  hidden: false,
  description: '',
  remark: ''
})

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入权限名称', trigger: 'blur' },
    { min: 2, max: 50, message: '权限名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入权限编码', trigger: 'blur' },
    { pattern: /^[A-Z_:]+$/, message: '权限编码只能包含大写字母、下划线和冒号', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择权限类型', trigger: 'change' }
  ],
  path: [
    { required: true, message: '请输入路径或接口地址', trigger: 'blur' }
  ],
  method: [
    { required: true, message: '请选择请求方式', trigger: 'change' }
  ]
}

// 树选择器配置
const treeSelectProps = {
  children: 'children',
  label: 'name',
  value: 'id'
}

// 模拟数据
const tableData = ref([
  {
    id: 1,
    name: '仪表盘',
    code: 'DASHBOARD',
    type: 'menu',
    parentId: null,
    path: '/dashboard',
    method: '',
    icon: 'dashboard',
    sort: 1,
    status: 1,
    hidden: false,
    description: '系统仪表盘页面',
    createTime: '2024-01-01 09:00:00',
    remark: '系统首页',
    children: [
      {
        id: 11,
        name: '查看仪表盘',
        code: 'DASHBOARD:VIEW',
        type: 'button',
        parentId: 1,
        path: '',
        method: '',
        icon: '',
        sort: 1,
        status: 1,
        hidden: false,
        description: '查看仪表盘数据权限',
        createTime: '2024-01-01 09:00:00',
        remark: '基础查看权限'
      }
    ]
  },
  {
    id: 2,
    name: '人力资源',
    code: 'HR',
    type: 'menu',
    parentId: null,
    path: '/hr',
    method: '',
    icon: 'user',
    sort: 2,
    status: 1,
    hidden: false,
    description: '人力资源管理模块',
    createTime: '2024-01-01 09:00:00',
    remark: '人事管理',
    children: [
      {
        id: 21,
        name: '员工管理',
        code: 'HR:EMPLOYEE',
        type: 'menu',
        parentId: 2,
        path: '/hr/employee',
        method: '',
        icon: 'user-group',
        sort: 1,
        status: 1,
        hidden: false,
        description: '员工信息管理',
        createTime: '2024-01-01 09:00:00',
        remark: '员工基础信息',
        children: [
          {
            id: 211,
            name: '查看员工',
            code: 'HR:EMPLOYEE:VIEW',
            type: 'button',
            parentId: 21,
            path: '',
            method: '',
            icon: '',
            sort: 1,
            status: 1,
            hidden: false,
            description: '查看员工列表权限',
            createTime: '2024-01-01 09:00:00',
            remark: '员工查看权限'
          },
          {
            id: 212,
            name: '新增员工',
            code: 'HR:EMPLOYEE:ADD',
            type: 'button',
            parentId: 21,
            path: '',
            method: '',
            icon: '',
            sort: 2,
            status: 1,
            hidden: false,
            description: '新增员工权限',
            createTime: '2024-01-01 09:00:00',
            remark: '员工新增权限'
          },
          {
            id: 213,
            name: '编辑员工',
            code: 'HR:EMPLOYEE:EDIT',
            type: 'button',
            parentId: 21,
            path: '',
            method: '',
            icon: '',
            sort: 3,
            status: 1,
            hidden: false,
            description: '编辑员工信息权限',
            createTime: '2024-01-01 09:00:00',
            remark: '员工编辑权限'
          },
          {
            id: 214,
            name: '删除员工',
            code: 'HR:EMPLOYEE:DELETE',
            type: 'button',
            parentId: 21,
            path: '',
            method: '',
            icon: '',
            sort: 4,
            status: 1,
            hidden: false,
            description: '删除员工权限',
            createTime: '2024-01-01 09:00:00',
            remark: '员工删除权限'
          }
        ]
      },
      {
        id: 22,
        name: '考勤管理',
        code: 'HR:ATTENDANCE',
        type: 'menu',
        parentId: 2,
        path: '/hr/attendance',
        method: '',
        icon: 'clock',
        sort: 2,
        status: 1,
        hidden: false,
        description: '员工考勤管理',
        createTime: '2024-01-01 09:00:00',
        remark: '考勤统计',
        children: [
          {
            id: 221,
            name: '查看考勤',
            code: 'HR:ATTENDANCE:VIEW',
            type: 'button',
            parentId: 22,
            path: '',
            method: '',
            icon: '',
            sort: 1,
            status: 1,
            hidden: false,
            description: '查看考勤记录权限',
            createTime: '2024-01-01 09:00:00',
            remark: '考勤查看权限'
          }
        ]
      }
    ]
  },
  {
    id: 3,
    name: '系统管理',
    code: 'SYSTEM',
    type: 'menu',
    parentId: null,
    path: '/system',
    method: '',
    icon: 'setting',
    sort: 10,
    status: 1,
    hidden: false,
    description: '系统管理模块',
    createTime: '2024-01-01 09:00:00',
    remark: '系统配置',
    children: [
      {
        id: 31,
        name: '用户管理',
        code: 'SYSTEM:USER',
        type: 'menu',
        parentId: 3,
        path: '/system/user',
        method: '',
        icon: 'user',
        sort: 1,
        status: 1,
        hidden: false,
        description: '系统用户管理',
        createTime: '2024-01-01 09:00:00',
        remark: '用户管理页面'
      },
      {
        id: 32,
        name: '角色管理',
        code: 'SYSTEM:ROLE',
        type: 'menu',
        parentId: 3,
        path: '/system/role',
        method: '',
        icon: 'role',
        sort: 2,
        status: 1,
        hidden: false,
        description: '系统角色管理',
        createTime: '2024-01-01 09:00:00',
        remark: '角色管理页面'
      },
      {
        id: 33,
        name: '权限管理',
        code: 'SYSTEM:PERMISSION',
        type: 'menu',
        parentId: 3,
        path: '/system/permission',
        method: '',
        icon: 'permission',
        sort: 3,
        status: 1,
        hidden: false,
        description: '系统权限管理',
        createTime: '2024-01-01 09:00:00',
        remark: '权限管理页面'
      }
    ]
  },
  {
    id: 4,
    name: '用户API',
    code: 'API:USER',
    type: 'api',
    parentId: null,
    path: '/api/users',
    method: 'GET',
    icon: '',
    sort: 1,
    status: 1,
    hidden: false,
    description: '获取用户列表接口',
    createTime: '2024-01-01 09:00:00',
    remark: 'API接口权限'
  },
  {
    id: 5,
    name: '创建用户API',
    code: 'API:USER:CREATE',
    type: 'api',
    parentId: null,
    path: '/api/users',
    method: 'POST',
    icon: '',
    sort: 2,
    status: 1,
    hidden: false,
    description: '创建用户接口',
    createTime: '2024-01-01 09:00:00',
    remark: 'API接口权限'
  }
])

// 计算属性
const isEdit = computed(() => !!formData.id)
const dialogTitle = computed(() => isEdit.value ? '编辑权限' : '新增权限')

// 方法
const loadData = async () => {
  loading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    // 构建父级选项
    buildParentOptions()
  } catch (error) {
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

const buildParentOptions = () => {
  const options = []
  const buildOptions = (data, level = 0) => {
    data.forEach(item => {
      if (item.type === 'menu') {
        options.push({
          id: item.id,
          name: '　'.repeat(level) + item.name,
          children: item.children ? [] : undefined
        })
        if (item.children) {
          buildOptions(item.children, level + 1)
        }
      }
    })
  }
  buildOptions(tableData.value)
  parentOptions.value = options
}

const getTypeLabel = (type) => {
  const typeMap = {
    menu: '菜单',
    button: '按钮',
    api: '接口'
  }
  return typeMap[type] || type
}

const getMethodType = (method) => {
  const methodMap = {
    GET: 'success',
    POST: 'primary',
    PUT: 'warning',
    DELETE: 'danger',
    PATCH: 'info'
  }
  return methodMap[method] || 'info'
}

const getPathPlaceholder = () => {
  const placeholderMap = {
    menu: '请输入菜单路径，如：/system/user',
    button: '按钮权限无需路径',
    api: '请输入接口地址，如：/api/users'
  }
  return placeholderMap[formData.type] || '请输入路径'
}

const handleSearch = () => {
  loadData()
}

const handleReset = () => {
  Object.assign(searchForm, {
    name: '',
    code: '',
    type: '',
    status: ''
  })
  handleSearch()
}

const handleAdd = () => {
  resetForm()
  dialogVisible.value = true
}

const handleAddChild = (row) => {
  resetForm()
  formData.parentId = row.id
  formData.type = 'button'
  dialogVisible.value = true
}

const handleEdit = (row) => {
  Object.assign(formData, { ...row })
  dialogVisible.value = true
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除权限 "${row.name}" 吗？删除后其子权限也将被删除！`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 模拟删除操作
    const deleteNode = (data, id) => {
      for (let i = 0; i < data.length; i++) {
        if (data[i].id === id) {
          data.splice(i, 1)
          return true
        }
        if (data[i].children && deleteNode(data[i].children, id)) {
          return true
        }
      }
      return false
    }
    
    deleteNode(tableData.value, row.id)
    ElMessage.success('删除成功')
    loadData()
  } catch {
    // 用户取消删除
  }
}

const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedPermissions.value.length} 个权限吗？`,
      '批量删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 模拟批量删除操作
    ElMessage.success('批量删除成功')
    selectedPermissions.value = []
    loadData()
  } catch {
    // 用户取消删除
  }
}

const handleToggleStatus = async (row) => {
  const action = row.status === 1 ? '禁用' : '启用'
  try {
    await ElMessageBox.confirm(
      `确定要${action}权限 "${row.name}" 吗？`,
      `${action}确认`,
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 模拟状态切换操作
    row.status = row.status === 1 ? 0 : 1
    ElMessage.success(`${action}成功`)
  } catch {
    // 用户取消操作
  }
}

const handleExpandAll = () => {
  const getAllKeys = (data) => {
    const keys = []
    data.forEach(item => {
      keys.push(item.id)
      if (item.children) {
        keys.push(...getAllKeys(item.children))
      }
    })
    return keys
  }
  expandedKeys.value = getAllKeys(tableData.value)
}

const handleCollapseAll = () => {
  expandedKeys.value = []
}

const handleExport = () => {
  ElMessage.success('导出功能开发中...')
}

const handleSelectionChange = (selection) => {
  selectedPermissions.value = selection
}

const handleTypeChange = (type) => {
  // 根据类型清空相关字段
  if (type === 'button') {
    formData.path = ''
    formData.method = ''
    formData.icon = ''
  } else if (type === 'api') {
    formData.icon = ''
    if (!formData.method) {
      formData.method = 'GET'
    }
  } else if (type === 'menu') {
    formData.method = ''
  }
}

const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    submitLoading.value = true
    
    // 模拟提交操作
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    if (isEdit.value) {
      // 编辑权限
      const updateNode = (data, updatedData) => {
        for (let item of data) {
          if (item.id === updatedData.id) {
            Object.assign(item, updatedData)
            return true
          }
          if (item.children && updateNode(item.children, updatedData)) {
            return true
          }
        }
        return false
      }
      updateNode(tableData.value, formData)
      ElMessage.success('权限更新成功')
    } else {
      // 新增权限
      const newPermission = {
        ...formData,
        id: Date.now(),
        createTime: new Date().toLocaleString()
      }
      
      if (formData.parentId) {
        // 添加到父节点
        const addToParent = (data, parentId, newItem) => {
          for (let item of data) {
            if (item.id === parentId) {
              if (!item.children) {
                item.children = []
              }
              item.children.push(newItem)
              return true
            }
            if (item.children && addToParent(item.children, parentId, newItem)) {
              return true
            }
          }
          return false
        }
        addToParent(tableData.value, formData.parentId, newPermission)
      } else {
        // 添加到根节点
        tableData.value.push(newPermission)
      }
      
      ElMessage.success('权限创建成功')
    }
    
    dialogVisible.value = false
    loadData()
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    submitLoading.value = false
  }
}

const handleDialogClose = () => {
  resetForm()
}

const resetForm = () => {
  Object.assign(formData, {
    id: null,
    name: '',
    code: '',
    type: 'menu',
    parentId: null,
    path: '',
    method: '',
    icon: '',
    sort: 0,
    status: 1,
    hidden: false,
    description: '',
    remark: ''
  })
  formRef.value?.clearValidate()
}

// 生命周期
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.permission-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e4e7ed;
}

.page-header h2 {
  margin: 0;
  color: #303133;
  font-size: 20px;
  font-weight: 600;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-section {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.table-section {
  background: white;
  border-radius: 8px;
  overflow: hidden;
}

.permission-name {
  display: flex;
  align-items: center;
  gap: 8px;
}

.permission-icon {
  font-size: 16px;
  color: #606266;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .header-actions {
    width: 100%;
    justify-content: flex-start;
    flex-wrap: wrap;
  }
  
  .search-section .el-form {
    flex-direction: column;
  }
  
  .search-section .el-form-item {
    margin-right: 0;
    margin-bottom: 15px;
  }
}
</style>